/*
 * Description: thread pool class.
 */

#include "thread_pool.h"

namespace COMMON {
ThreadPool::ThreadPool(size_t threads)
{
    auto func = [this] {
        while (true) {
            using FUNC_TYPE = void();
            std::function<FUNC_TYPE> task;

            {
                std::unique_lock<std::mutex> lock(this->m_queueMutex);
                this->m_condition.wait(lock, [this] { return this->m_stopped || (!this->m_tasks.empty()); });
                if (this->m_stopped && this->m_tasks.empty()) {
                    return;
                }
                task = std::move(this->m_tasks.front());
                this->m_tasks.pop();
            }

            task();
        }
    };

    for (size_t i = 0; i < threads; ++i) {
        m_workers.emplace_back(func);
    }
}


ThreadPool::~ThreadPool()
{
    {
        std::unique_lock<std::mutex> lock(m_queueMutex);
        m_stopped = true;
    }
    m_condition.notify_all();
    for (auto &worker: m_workers) {
        worker.join();
    }
}
}